#! /usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'abcdefg'
__time__ = '21/06/18 下午9:51'

from . import index_blu
from info.models import User, News, Category
# from info import redis_store
from flask.json import jsonify

from flask import render_template, current_app, session, request

from info import constants
from info.utils.response_code import RET


@index_blu.route('/')
def index():
    """
    首页,用户登陆逻辑
    1. 如果登陆 将登陆数据传入模板 显示头像昵称
    :return:
    """
    user_id = session.get("userid", None)

    user = None  # 以免查询错误出错

    if user_id:
        try:
            user = User.query.get(user_id)
        except Exception as e:
            current_app.logger.error(e)

    # 右侧新闻排行榜的逻辑
    news_list_top = list()
    try:
        news_list_top = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)

    # 定义空字典列表 里面装字典
    news_dict_li = list()

    # 遍历对象列表，将对象的字典添加到字典列表中
    for news in news_list_top:
        news_dict_li.append(news.to_basic_dict())

    # 查询分类数据 通过模板渲染
    categories = Category.query.all()

    category_li = list()
    for category in categories:
        category_li.append(category.to_dict())

    # 待传入模板的字典
    data = {
        "user": user.to_dict() if user else None,
        "news_dict_li": news_dict_li,
        "category_li": category_li
    }

    return render_template('news/index.html', data=data)


@index_blu.route('/favicon.ico')
def favicon():
    return current_app.send_static_file('news/favicon.ico')


@index_blu.route('/news_list')
def news_list():
    """
    获取首页新闻数据
    :return:
    """
    # 1. 获取参数
    cid = request.args.get('cid', '1')
    page = request.args.get('page', '1')
    per_page = request.args.get('per_page', '10')

    # 2. 校验数据
    try:
        cid = int(cid)
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 3. 查询数据
    filters = list()
    if cid != 1:
        # 需要添加条件
        filters.append(News.category_id == cid)

    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, per_page, False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")

    # 取当前页数据 # 模型对象列表
    news_model_list = paginate.items
    total_page = paginate.pages
    current_page = paginate.page

    news_dict_li = list()
    for news in news_model_list:
        news_dict_li.append(news.to_basic_dict())

    data = {
        "total_page": total_page,
        "current_page": current_page,
        "news_dict_li": news_dict_li
    }

    return jsonify(errno=RET.OK, errmsg="OK", data=data)
